from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse, reverse_lazy
from django.views import View

from . import models
from database.forms import CanteenForm, StoreForm, FoodForm, OrderCreateForm, NormalUserUpdateForm
from django.views.generic import ListView, CreateView, DetailView, DeleteView, UpdateView


# Create your views here.

'''
------------------------------------
          
           Administrator
           
------------------------------------
'''

# listView面向多个对象（整个表）
class CanteenList(ListView):

    model = models.Canteen # 取数据的地方
    # template_name = 'database/canteen_list.html' # 渲染到的地方

    def __init__(self):
        super().__init__()
        self.my_id = 0

    def get(self, request, *args,**kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.Administrator.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        # print(account)
        queryset = models.Canteen.objects.filter(adm_id=self.my_id)
        return render(request, 'database/canteen_list.html', {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class CanteenCreateView(CreateView):
    form_class = CanteenForm
    model = models.Canteen
    def __init__(self):
        super().__init__()
        self.my_id = 0

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        return render(request, 'database/canteen_create.html', {"adm_id": str(self.my_id)})

    # 提交以后由该方法处理数据
    def post(self, request, *args, **kwargs):
        # 验证数据
        data = request.POST
        self.my_id = data['adm_id']
        form = CanteenForm(data=data)
        if form.is_valid():
            # 保存数据
            canteen = models.Canteen(
                id=form.cleaned_data['id'],
                name=form.cleaned_data['name'],
                address=form.cleaned_data['address'],
                telNum=form.cleaned_data['telNum'],
                adm_id=form.cleaned_data['adm_id'],
            )
            canteen.save()
        else:
            raise Exception

        # 跳转
        return HttpResponseRedirect(reverse('delivery_database:canteen_list', args=[self.my_id])) # 反向解析url并返回

class CanteenDetail(DetailView):
    model = models.Canteen
    template_name = 'database/canteen_detail.html'
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)


class CanteenDelete(DeleteView):
    model = models.Canteen
    template_name = 'database/canteen_delete.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_model = self.get_object()
        return reverse(
            'delivery_database:canteen_list',
            kwargs={
                'int': str(int(my_model.adm_id))
            }
        )

class CanteenUpdate(UpdateView):
    model = models.Canteen
    form_class = CanteenForm
    template_name = "database/canteen_update.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_model = self.get_object()
        return reverse(
            'delivery_database:canteen_list',
            kwargs={
                'int': str(int(my_model.adm_id))
            }
        )

'''
------------------------------------

              Seller

------------------------------------
'''

class SellerMenu(View):
    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.Seller.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        print(account)
        queryset = models.Canteen.objects.filter(adm_id=self.my_id)
        return render(request, 'database/seller_menu.html', {"object_list": queryset, "id": self.my_id, "name": name})


'''
------------------------------------

              Store

------------------------------------
'''

class StoreList(ListView):

    model = models.storeInfo # 取数据的地方
    # template_name = 'database/seller_store_list.html' # 渲染到的地方

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.Seller.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        queryset = models.storeInfo.objects.filter(sel_id=self.my_id)
        return render(request, 'database/seller_store_list.html', {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class StoreDetail(DetailView):
    model = models.storeInfo
    template_name = 'database/seller_store_detail.html'
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

class StoreDelete(DeleteView):
    model = models.storeInfo
    template_name = 'database/seller_store_delete.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_model = self.get_object()
        return reverse(
            'delivery_database:seller_store_list',
            kwargs={
                'int': str(int(my_model.sel_id))
            }
        )

class StoreUpdate(UpdateView):
    model = models.storeInfo
    form_class = StoreForm
    template_name = "database/seller_store_update.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_model = self.get_object()
        return reverse(
            'delivery_database:seller_store_list',
            kwargs={
                'int': str(int(my_model.sel_id))
            }
        )

class StoreCreateView(CreateView):
    form_class = StoreForm
    model = models.storeInfo
    def __init__(self):
        super().__init__()
        self.my_id = 0

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        return render(request, 'database/seller_store_create.html', {"sel_id": str(self.my_id)})

    # 提交以后由该方法处理数据
    def post(self, request, *args, **kwargs):
        # 验证数据
        data = request.POST
        self.my_id = data['sel_id']
        form = StoreForm(data=data)
        if form.is_valid():
            # 保存数据
            store = models.storeInfo(
                id=form.cleaned_data['id'],
                sel_id=form.cleaned_data['sel_id'],
                can_id=form.cleaned_data['can_id'],
                name=form.cleaned_data['name'],
                reletiveAddress=form.cleaned_data['reletiveAddress'],
                telNum=form.cleaned_data['telNum'],
            )
            store.save()
        else:
            raise Exception

        # 跳转
        return HttpResponseRedirect(reverse('delivery_database:seller_store_list', args=[self.my_id])) # 反向解析url并返回

'''
------------------------------------

            food(seller)

------------------------------------
'''

class FoodList(ListView):

    template_name = 'database/seller_food_list.html' # 渲染到的地方

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.Seller.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        my_store_id = models.storeInfo.objects.filter(sel_id=self.my_id).values("id")
        queryset = models.food.objects.filter(sto_id__in = my_store_id)
        return render(request, 'database/seller_food_list.html',
                      {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class FoodDetail(DetailView):
    model = models.food
    template_name = 'database/seller_food_detail.html'
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

class FoodCreateView(CreateView):
    form_class = FoodForm
    model = models.food
    def __init__(self):
        super().__init__()
        self.my_id = 0

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        return render(request, 'database/seller_food_create.html', {"id": str(self.my_id)})

    # 提交以后由该方法处理数据
    def post(self, request, *args, **kwargs):
        # 验证数据
        data = request.POST
        self.my_id = data['sto_id']
        self.my_id = models.storeInfo.objects.filter(id=self.my_id).values("sel_id").first().get("sel_id")
        form = FoodForm(data=data)
        if form.is_valid():
            # 保存数据
            food1 = models.food(
                id=form.cleaned_data['id'],
                sto_id=form.cleaned_data['sto_id'],
                name=form.cleaned_data['name'],
                price=form.cleaned_data['price'],
            )
            food1.save()
        else:
            raise Exception

        # 跳转
        return HttpResponseRedirect(reverse('delivery_database:seller_food_list', args=[self.my_id])) # 反向解析url并返回

class FoodDelete(DeleteView):
    model = models.food
    template_name = 'database/seller_food_delete.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_sto_id = self.get_object().sto_id
        my_id = models.storeInfo.objects.filter(id=my_sto_id).values("sel_id").first().get("sel_id")
        return reverse(
            'delivery_database:seller_food_list',
            kwargs={
                'int': str(my_id)
            }
        )

class FoodUpdate(UpdateView):
    model = models.food
    form_class = FoodForm
    template_name = "database/seller_food_update.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_sto_id = self.get_object().sto_id
        my_id = models.storeInfo.objects.filter(id=my_sto_id).values("sel_id").first().get("sel_id")
        return reverse(
            'delivery_database:seller_food_list',
            kwargs={
                'int': str(my_id)
            }
        )

'''
------------------------------------

            order(seller)

------------------------------------
'''

class OrderList(ListView):

    template_name = 'database/seller_order_list.html' # 渲染到的地方

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.Seller.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        my_store_name = models.storeInfo.objects.filter(sel_id=self.my_id).values("name")
        queryset = models.orderInfo.objects.filter(store_name__in = my_store_name)
        return render(request, 'database/seller_order_list.html',
                      {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class OrderDetail(DetailView):
    model = models.orderInfo
    template_name = 'database/seller_order_detail.html'
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

class OrderUpdate(UpdateView):
    model = models.order
    form_class = OrderCreateForm
    template_name = "database/seller_order_update.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        order_id = self.get_object().id
        store_name = models.orderInfo.objects.filter(id=order_id).values("store_name").first().get("store_name")
        my_id = models.storeInfo.objects.filter(name=store_name).values("sel_id").first().get("sel_id")
        return reverse(
            'delivery_database:seller_order_list',
            kwargs={
                'int': str(my_id)
            }
        )

'''
------------------------------------

            NormalUser

------------------------------------
'''

class NormalUserMenu(View):
    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.NormalUser.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        print(account)
        queryset = models.Canteen.objects.filter(adm_id=self.my_id)
        return render(request, 'database/normal_user_menu.html', {"object_list": queryset, "id": self.my_id, "name": name, })

class NormalUserSetting(UpdateView):
    model = models.NormalUser
    form_class = NormalUserUpdateForm
    template_name = "database/normal_user_setting.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)

    def get_success_url(self):
        my_id = self.get_object().id
        return reverse(
            'delivery_database:normal_user_menu',
            kwargs={
                'int': str(my_id)
            }
        )

'''
------------------------------------

          food(normalUser)

------------------------------------
'''

class NormalUserFoodList(ListView):

    template_name = 'database/normal_user_food_list.html' # 渲染到的地方

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.NormalUser.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        queryset = models.food.objects.filter()
        return render(request, 'database/normal_user_food_list.html',
                      {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class NormalUserFoodOrder(View):
    def __init__(self):
        super().__init__()
        self.my_id = 0

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('id'))
        self.pk = int(kwargs.get('pk'))
        return render(request, 'database/normal_user_food_order.html', {"id": str(self.my_id), 'pk': str(self.pk)})

    # 提交以后由该方法处理数据
    def post(self, request, *args, **kwargs):
        # 验证数据
        data = request.POST
        # 保存数据
        order1 = models.order(
            nor_id=data['id'],
            orderTime=None,
        )
        order1.save()

        use_id = models.order.objects.filter(nor_id=data['id']).values("id").last().get("id")

        orderedFood1 = models.orderedFood(
            use_id=use_id,
            uid=data['uid'],
            amount=data['amount'],
        )
        orderedFood1.save()

        # 跳转
        return HttpResponseRedirect(reverse('delivery_database:normal_user_menu', args=[data['id']])) # 反向解析url并返回

'''
------------------------------------

         order(normalUser)

------------------------------------
'''

class NormalUserOrderList(ListView):

    template_name = 'database/normal_user_order_list.html' # 渲染到的地方

    def get(self, request, *args, **kwargs):
        self.my_id = int(kwargs.get('int'))
        account = models.NormalUser.objects.filter(id=self.my_id).values("account").first().get("account")
        account = int(account)
        name = models.UserInfo.objects.filter(account=account).values("userName").first().get("userName")
        queryset = models.orderInfo.objects.filter(account = account)
        return render(request, 'database/normal_user_order_list.html',
                      {"object_list": queryset, "id": self.my_id, "name": name})

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        return context

class NormalUserOrderDetail(DetailView):
    model = models.orderInfo
    template_name = 'database/normal_user_order_detail.html'
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        context['id'] = int(kwargs.get('id'))
        return self.render_to_response(context)